package com.jiyun.wait.config;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.jiyun.pojo.chat.ChatMessage;
import com.jiyun.wait.service.impl.ChatMessageServiceImpl;
import com.jiyun.wait.service.impl.WaitServiceImpl;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint(value = "/websocket/message/{userId}")
@Component
public class WebSocketMessage {
    private static Logger l= LoggerFactory.getLogger(WebSocketMessage.class);
    private String userId;

    private static Map<String,Session> sessionMap=new ConcurrentHashMap();

    private static ChatMessageServiceImpl ns;

    //通过类注入的方式注入service类
    @Autowired
    public void setWaitServiceImpl(ChatMessageServiceImpl noticeService) {
        WebSocketMessage.ns = noticeService;
    }


    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        boolean flag = sessionMap.containsKey(userId);
        if (!flag){
            sessionMap.put(userId,session);
        }
        this.userId=userId;
        log.info("连接建立");
    }
    @OnClose
    public void onClose(@PathParam("userId") String userId) {
        if (!ObjectUtils.isEmpty(userId)){
            sessionMap.remove(userId);
        }
        log.info("连接关闭");
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            log.info("收到消息,{}", message);
            //将JSON字符串转换为对象
            ChatMessage chatMessage = JSON.parseObject(message, ChatMessage.class);
            //时间为当前时间
            chatMessage.setTime(DateUtil.date());
            int save = ns.save(chatMessage);
            //将对象转换为JSON字符串
            String chatMessage1 = JSON.toJSONString(chatMessage);
            if (save>0){
                //发送到所有端口
                sendMessage(chatMessage1);
            }else {
                session.getBasicRemote().sendText("保存失败");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendMessage(String message) throws IOException {
        try {
            for (Session session : sessionMap.values()) {
                session.getBasicRemote().sendText(message);
            }
        }catch (IOException e){
            throw e;
        }
    }
}
